/**
 * 編集フォーム入力支援 
 */
$(function(){

    /**
     *削除確認
     */
    $('input[name=delete]').click(function(){
        if (window.confirm('このエントリを削除します。')) {
            return true;
        } else {
            return false;
        }
    });

    /**
     *編集テキストエリア 
     */
    $(".draggable_textarea").draggable({
        start : function (event , ui){
            $(this).css({'right':'auto'});
        } 
    });

    /**
     *数字限定 
     */
    $('.table_form .form_number').bind('change keyup', function(){
        
        var val = $(this).val();
        val = val.replace(/[^0-9]/g, '');
        
        if (!val) val = 0;
        val = parseInt(val);
        
        $(this).val(val);
        
    });

    /**
     *ひらがな限定 
     */
    $('.table_form .form_hiragana').bind('change keyup', function(){
        
        var val = $(this).val();
        val = val.replace(/[^ぁ-ん]/g, '');
        
        $(this).val(val);
        
    });

    /**
     *最低文字数
     */
    $('.form_repass,.form_pass').bind('change keyup', function(){
        pass = $('.form_pass');
        repass = $('.form_repass');
        
        val_pass = pass.val();
        val_repass = repass.val();
        
        formError(pass, (val_pass!=val_repass));
        formError(repass, (val_pass!=val_repass));
        //minlength
        //val = val.replace(/[^ぁ-ん_ー]/g, '');
        
        //$(this).val(val);
        
    });

    /**
     *フォームエラー出力
     */
    function formError(target, error)
    {
        if (error) $(target).css({'background-color':'red'});
        else $(target).css({'background-color':'none'});
    }


    /**
     * リンク紐付け 
     */
    $('.link_form_add').each(function(){
        
        var self = this;
        $('input',self).bind('change keyup', function(){
        });
    });

    /**
     *カテゴリ入力 
     */
    $('.form_multiple_input').each(function(){
        
        var self = this;
        
        $('input.remove', self).click(function(){
            $(this).parent().remove();
        });
        
        $('.add', self).click(function(){

            var value = $('.input', self).val();
            if (!value) return false;
            var type  = $(self).attr('et_value');
            var mode  = $('select option:selected', self).attr('et_mode');
            var id    = $('select option:selected', self).val();
            var index = parseInt($(self).attr('et_count'));
            if (!index) index = 0;
            
            $('.input', self).val('');
            $('.add', self).attr('disabled','disabled');
            $('select', self).attr('disabled','disabled');
            $(self).attr('et_count',(index+1));
            
            var obj = $('<li/>');
                $(obj).append("\n");
            obj.append($('<input/>',{
                type:'button',
                value:'除外',
                class:'remove'
            }).click(function(){
                $(this).parent().remove();
            }));
            
            function publishValues (obj, index, id, href, label, type, mode, array)
            {
                $(obj).append("\n");
                obj.append($('<input/>',{ type:'hidden', name:'_category[' + index + '][category_id]', value:type}));
                $(obj).append("\n");
                obj.append($('<input/>',{ type:'hidden', name:'_category[' + index + '][category_list_id]', value:id}));
                $(obj).append("\n");
                obj.append($('<input/>',{ type:'hidden', name:'_category[' + index + '][slug]', value:mode}));
                for (i = 0; i < array.length; i++) {
                    $(obj).append("\n");
                    obj.append($('<input/>',{
                        type:'hidden',
                        name:'_category[' + index + '][parameter_'+(i+1)+']',
                        value:array[i]
                    }));
                }
                $(obj).append("\n");
                obj.append($('<a>',{href:href, target:'_blank'}).text(label+'（'+href+'）'));
                $('ul', self).append(obj);
                $('ul', self).append("\n");
            }
            
            switch (mode) {
                case 'hp':
                    publishValues(obj, index, id, value, 'ホームページ', type, mode, [value]);
                    break;
                case 'twitter':
                    publishValues(obj, index, id, value, 'Twitterリンク', type, mode, [value,12]);
                    break;
                default:
                    break;
            }
            $('select', self).removeAttr('disabled','disabled');
        });
        
        $('.input', self).bind('change keyup', function(){
            if ($(this).val().length > 0) $('.add', self).removeAttr('disabled');
            else $('.add', self).attr('disabled','disabled');
        }).bind('keydown', function(e){
             var code = e.keyCode || e.which;
             if (code == 13) {
                 $('.add', self).trigger('click');
                 return false;
             }
        });
    });


    /**
     * ソート 
     */
    $('.sortable').sortable({
        cursor: 'move',
        opacity: 0.7,
        placeholder: 'ui-state-highlight',
    })
    .disableSelection().delegate('input,textarea','click',function(ev){
        ev.target.focus();
    });

    /**
     * オートコンプリート 
     */
    $('.link_form_add').each(function(index){
        var self = this;
        var target = $(self).attr('et_target');
        var remove = $(self).attr('et_remove');
        var yaku   = $(self).attr('et_yaku');
        var me     = $(self).attr('et_me');
        
        $('.remove', self).click(function(){
            me = removeThat(this, me);
            return false;
        });

        $("input.add", self).autocomplete({
            source: function(req, resp){
                $.ajax({
                    url:target,
                    type:'GET',
                    cache:false,
                    dataType:'json',
                    data:{
                        s:req.term,
                        m:me
                    },
                    success:function(o){
                        resp(o.items);
                        if (!o.total) {
                            var href = $('.add_link a', self).attr('et_href');
                            href += $("input.add", self).val();
                            $('.add_link a', self).attr('href', href);
                            $('.add_link', self).show();
                        } else {
                            $('.add_link', self).hide();
                        }
                    },
                    error:function(xhr, ts, err){
                        console.log('ajax error');
                        resp(['']);
                    }
                });
            },
            autoFocus: true,
            delay: 500,
            minLength: 2,
            select:function(event, ui) {
                var date = new Date();
                var index = date.getTime();
                me += "," + ui.item.val;
                var obj = $('<li/>',{class:'link_form'});
                obj.append($('<button/>').text(remove).click(function(){
                    me = removeThat(this, me);
                    return false;
                }));
                obj.append($('<input/>',{type:'hidden',name:'_target[' + index + ']',class:'link_form_target'}).val(ui.item.val));
                obj.append($('<input/>',{type:'hidden',name:'_yaku[' + index + ']'}).val(yaku));
                obj.append($('<input/>',{type:'hidden',name:'_sort[' + index + ']'}).val(1));
                obj.append("\n");
                obj.append(ui.item.label);
                obj.append($('<input/>',{type:'text',name:'_note[' + index + ']'}));
                $(".sortable",self).append(obj);
                $(".sortable",self).append('\n');
            },
            close:function(event, ui) {
                $("input.add", self).val('');
            }
          });
        
    });
    function removeThat (that, me)
    {
        var child = $('.link_form_target', $(that).parent()).val();
        var array = me.split(',');
        for( i = 0; i < array.length; i++){
            if( array[i] == child ){
                array.splice(i, 1);
            }
        }
        me = array.join();
        $(that).parent().remove();
        return me;
    }


    /**
     * 発売日
     */
    $(".form_release").datepicker({
        showButtonPanel: true,
        dateFormat: 'yymmdd',
        changeMonth: true,
        changeYear: true,
        autoClose: true,
        beforeShow: function( input, inst ) {
            setTimeout(function() {
                var month  = inst.selectedMonth + 1;
                var year   = inst.selectedYear;
                addButtonsToDatePicker( month, year, input, this );
            }, 1 );
        },
        onChangeMonthYear: function( year, month, instance ) {
            setTimeout(function() {
                addButtonsToDatePicker( month, year, instance.input, this );
            }, 1 );
        },
        onSelect: function (result, inst) {
            showResultDatePicker(result, this);
        }
    })
    .bind('change keyup', function(){
        
        var val = $(this).val();
        val = val.replace(/[^0-9]/g, '');
        $(this).val(val);
        
        showResultDatePicker(val, this);
    });
    function showResultDatePicker (ymd, self)
    {
        var release = ymdToRelease(ymd);
        $("span", $(self).next()).text(release);
    }
    function addButtonsToDatePicker (month, year, input, self)
    { 
        var params = [
            0,0,
            month+'月',0,
            "予定", year + (("0"+month).slice(-2)) + 44,
            "上旬", year + (("0"+month).slice(-2)) + 41,
            "中旬", year + (("0"+month).slice(-2)) + 42,
            "下旬", year + (("0"+month).slice(-2)) + 43,
            0,0,
            year,0,
            "予定", year + "9999",
            "前半", year + "0666",
            "後半", year + "1266",
            "初頭", year + "0266",
            "末", year + "1277",
            0,0,
            year,0,
            "春", year + "0588",
            "夏", year + "0888",
            "秋", year + "1188",
            "冬（年内）", year + "1288",
            "冬", (year+1) + "0288",
            0,0,
            year,0,
            "夏コミ", year + "0840",
            "冬コミ", year + "1240",
            0,0,
            year,0,
            "第1四半期", year + "0355",
            "2", year + "0655",
            "3", year + "0955",
            "4", year + "1255",
            0,0,
            "未定", 88888888,
            "未発表", 22221111,
            "なし", 90000000,
            "中止", 11111111,
        ];
    
        var buttonPane = $( input )
            .datepicker( "widget" )
            .find( ".ui-datepicker-buttonpane" );
        
        for (i = 0; i < params.length; i+=2) {
            var text = params[i];
            var click = params[i+1];
            
            var obj = (text && click) ?
                $( "<button>", {
                    text: text,
                    'et_datepicker_val': click,
                    click: function () {
                        var result = $(this).attr('et_datepicker_val');
                        $.datepicker._clearDate( input );
                        $(input).val(result);
                        showResultDatePicker(result, input, self);
                    }
                }).addClass("ui-state-default ui-state-small")
            : (text) ?
                $( "<span>", {
                    text: text
                })
            :
                $("<hr>");
            
            obj.insertBefore( buttonPane );
        }
    }
    
});

/**
 * YYYYMMDD形式の数値を発売日表記に変更して返す 
 */
function ymdToRelease (x)
{
    var num = '';
    if (x.length > 0) {
        for ( var i = 0; i < x.length; i++ ) {
            num += x.substring(i,i+1).replace(/[^0-9]/g,'');
        }
    }
    if (num.length != 8) {
        str = "-";
    } else {
        switch (num) {
            case '11111111': str = "中止"; break;
            case '88888888': str = "未定"; break;
            case '90000000': str = "なし"; break;
            default:
                numY = num.substr(0,4) + "年";
                switch (num.substr(4)) {
                    case '9999': str = numY + "予定"; break;
                    case '1299': str = numY + "後半"; break;
                    case '0699': str = numY + "前半"; break;
                    case '1288': str = numY + "冬"; break;
                    case '0288': str = "冬"; break;
                    case '0588': str = numY + "春"; break;
                    case '0888': str = numY + "夏"; break;
                    case '1188': str = numY + "秋"; break;
                    case '1277': str = numY + "末"; break;
                    case '1266': str = numY + "後半"; break;
                    case '0666': str = numY + "前半"; break;
                    case '0266': str = numY + "初頭"; break;
                    case '1255': str = numY + "第4四半期"; break;
                    case '0955': str = numY + "第3四半期"; break;
                    case '0655': str = numY + "第2四半期"; break;
                    case '0355': str = numY + "第1四半期"; break;
                    case '0840': str = numY + "夏コミ"; break;
                    case '1240': str = numY + "冬コミ"; break;
                    default:
                        str = numY + num.substr(4,2) + "月";
                        numD = num.substr(6,2);
                        switch (numD) {
                            case '44': str += "予定"; break;
                            case '43': str += "下旬"; break;
                            case '42': str += "中旬"; break;
                            case '41': str += "上旬"; break;
                            default : str += numD + "日"; break;
                        }
                        break;
                }
                break;
        }
    }
    return str;
}

